package com.woniuxy.controller;

import com.woniuxy.entity.User;
import com.woniuxy.service.AuthService;
import com.woniuxy.utils.JWTUtil;
import com.woniuxy.utils.ResponseResults;
import com.woniuxy.utils.ResponseState;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private AuthService authService;

    @PostMapping("/login")
    public ResponseResults<User> login(@RequestBody User user, HttpServletResponse response){
        System.out.println("account:"+user.getAccount());
        User login = authService.Login(user);
        System.out.println("login的account"+login.getAccount());
        // 生成令牌
        String token = JWTUtil.generateToken(login.getId());
        // 将token放到响应头
        response.setHeader("authorization", token);
        System.out.println("token"+token);
        // 自定义响应头必须要进行暴露，暴露给浏览器（告诉前端头没问题）
        response.setHeader("Access-Control-Expose-Headers","authorization");
        // 成功
        return new ResponseResults<User>()
                .setCode(200)
                .setState(ResponseState.LOGIN_SUCCESS)
                .setMsg("登录成功！")
                .setData(login);
    }

}
